#include "TFly_list.h"
#include "script.h"
#include "script_block.h"
#include "script_debug.h"
#include "script_include.h"
#include "script_keyword.h"
#include "script_var.h"

script_exp_t *script_exp_create(int line,exp_node_t *node)
{
	script_exp_t *exp = script_calloc(1,sizeof(script_exp_t));
	exp->line = line;
	exp->exp = node;
	return exp;
}

void script_exp_destroy(script_exp_t *exp)
{
	if(exp){
		if(exp->exp){
			exp_node_list_destroy(exp->exp);
		}
		script_free(exp);
	}
}

script_code_block_t *script_code_block_create(script_t *script)
{
	script_code_block_t *block = script_calloc(1,sizeof(script_code_block_t));
	if(block == NULL){
		return NULL;
	}

	block->exp_list = TFly_list_create();
	TFly_list_add(block->exp_list,script_exp_create(0,exp_node_create(EXP_NODE_TYPE_CONST_NULL,NULL)));
	block->vars = exp_var_create(NULL);
	block->vars->type = EXP_VAR_TYPE_STRUCT;
	block->vars->object = exp_object_create();
	block->script = script;

	return block;
}

void script_code_block_destroy(script_code_block_t *block)
{
	if(block == NULL){
		return;
	}

	if(block->vars){
		exp_var_destroy(block->vars);
		block->vars = NULL;
	}

	if(block->exp_list){
		script_exp_t *tmp = TFly_list_del_first(block->exp_list);
		while(tmp){
			script_exp_destroy(tmp);
			tmp = TFly_list_del_first(block->exp_list);
		}
		TFly_list_destroy(block->exp_list);
	}

	script_free(block);
}

script_exec_block_t *script_exec_block_create(script_code_block_t *c_block)
{
	script_exec_block_t *block = script_calloc(1,sizeof(script_exec_block_t));
	block->vars = exp_var_create(NULL);
	block->vars->type = EXP_VAR_TYPE_STRUCT;
	block->vars->object = exp_object_create();
	block->item = TFly_list_get_item(c_block->exp_list);
	block->type = c_block->type;
	block->script = c_block->script;
	block->vars->name = script_calloc(1,8);
	strcpy(block->vars->name,"GLOBAL");
	//printf("\033[32m%s %d exec_block:%p\033[0m\r\n",__func__,__LINE__,block);
	return block;
}

void script_exec_block_destroy(script_exec_block_t *block)
{
	if(block == NULL){
		return;
	}

	if(block->item){
		TFly_list_item_destroy(block->item);
		block->item = NULL;
	}
	if(block->vars){
		exp_var_destroy(block->vars);
		block->vars = NULL;
	}

	script_free(block);
}

void show_block(script_code_block_t *block, int deep)
{
	if(block == NULL){
		return;
	}

	char *pex = script_calloc(1,deep*4+1);
	int i;
	for(i = 0; i < deep; i++) {
		sprintf(pex,"%s    ",pex);
	}

	exp_var_t *var = block->vars;

	if(var){
		show_exp_var(var,deep+1);
	}

#if 0
	exp_node_t *node = TFly_list_get_first(block->exp_list);
	while(node){
		printf("%s",pex);
		exp_node_print(node);
		node = TFly_list_get_next(block->exp_list);
	}
#endif

	script_free(pex);
}

